import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/DynamicItem.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';
import 'package:toys_flutter/pages/DynamicDetail.dart';

class DynamicList extends StatefulWidget {
  const DynamicList({super.key});

  @override
  State<DynamicList> createState() => _DynamicListState();
}

class _DynamicListState extends State<DynamicList>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin<DynamicList> {
  @override
  bool get wantKeepAlive => true;

  int tabIndex = 0;
  List<Map<String, dynamic>> _navList = [];
  List<dynamic> _list = [];
  bool isMore = true;
  final Map<String, dynamic> _params = {
    'page_no': 1,
    'cate_id': "",
    'is_recommend': 1,
  };
  late TabController _tabController;
  late ScrollController _scrollController;

  Future<void> _getNavData() async {
    try {
      var res = await Api.communityCate();
      if (res['code'] == 1) {
        setState(() {
          _navList = List<Map<String, dynamic>>.from(res['data']);
          _navList.insert(0, {'name': '热门推荐', 'id': '00001'});
          _navList.insert(1, {'name': '最新', 'id': '00002'});
        });
      } else {
        TDToast.showText('加载分类失败', context: context);
      }
    } catch (e) {
      TDToast.showText('加载分类异常: $e', context: context);
    }
  }

  Future<void> _initData(bool add) async {
    var res = await Api.communityNewArticleLists(_params);
    if (res['code'] == 1) {
      var list = List<Map<String, dynamic>>.from(res['data']['list']);
      setState(() {
        if (add) {
          _list.addAll(list);
        } else {
          _list = list;
        }
        isMore = res['data']['more'] != 0;
      });
    } else {
      TDToast.showText('加载数据失败', context: context);
    }
  }

  void getData(bool add) async {
    var res = await Api.communityArticleLists(_params);
    if (res['code'] == 1) {
      var list = List<Map<String, dynamic>>.from(res['data']['list']);
      setState(() {
        if (add) {
          _list.addAll(list);
        } else {
          _list = list;
        }
        isMore = res['data']['more'] != 0;
      });
    } else {
      TDToast.showText('加载数据失败', context: context);
    }
  }

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _initialize();
  }

  Future<void> _initialize() async {
    await _getNavData();
    _tabController = TabController(length: _navList.length, vsync: this);
    _initData(false);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _refreshData() async {
    _params['page_no'] = 1;
    isMore = true;
    _initialize();
    if (tabIndex == 0 || tabIndex == 1) {
      _initData(false);
    } else {
      getData(false);
    }
  }

  Future<void> _onLoadMore() async {
    if (!isMore) return;
    _params['page_no']++;
    if (tabIndex == 0 || tabIndex == 1) {
      _initData(true);
    } else {
      getData(true);
    }
  }

  void _handleTap(Map<String, dynamic> item) async {
    final String id = item['id'].toString();
    Get.to(DynamicDetail(id: id));
  }

  void _onTabTapped(int index) {
    setState(() {
      tabIndex = index;
      _params['page_no'] = 1;
      isMore = true;
      // _scrollController.jumpTo(0); // 切换Tab时滚动到顶部

      if (index == 0) {
        _params['is_recommend'] = 1;
        _initData(false);
      } else if (index == 1) {
        _params['is_recommend'] = 0;
        _initData(false);
      } else {
        _params['cate_id'] = _navList[index]['id'];
        getData(false);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        if (_navList.isNotEmpty)
          TDTabBar(
            tabs: _navList
                .map((item) => TDTab(text: item['name'].toString()))
                .toList(),
            controller: _tabController,
            isScrollable: true,
            showIndicator: true,
            dividerHeight: 0,
            onTap: _onTabTapped,
          ),
        if (_navList.isEmpty)
          const Center(
            child: CircularProgressIndicator(),
          ),
        Expanded(
          child: RefreshableListView(
            enableLoadMore: true,
            onLoadMore: _onLoadMore,
            onRefresh: _refreshData,
            children: [
              ..._list.map((item) => Column(
                    children: [
                      DynamicItem(
                        onTap: () => _handleTap(item),
                        item: item,
                      ),
                      const TDDivider(),
                    ],
                  )),
              TDDivider(
                text: isMore ? '上拉加载更多' : '没有更多了',
                alignment: TextAlignment.center,
              ),
              const SizedBox(height: 25),
            ],
          ),
        ),
      ],
    );
  }
}
